package de.stefanocke.roo.wicket.form.formfields

import de.stefanocke.roo.wicket.Stereotypes
import de.stefanocke.roo.wicket.base.BeanPropertiesAwareItdBuilder
import de.stefanocke.roo.wicket.form.FormComponentMetadata
import de.stefanocke.roo.wicket.model.BeanPropertyMetadata
import de.stefanocke.roo.wicket.model.BeanPropertyMetadataWithDetails
import java.lang.reflect.Modifier
import org.springframework.roo.classpath.details.ClassOrInterfaceTypeDetails
import org.springframework.roo.classpath.details.MethodMetadata

import static de.stefanocke.roo.xtend.Method.*
import static de.stefanocke.roo.xtend.MethodSignature.*

import static extension de.stefanocke.roo.wicket.base.WicketItdBuilder.*
import static extension de.stefanocke.roo.xtend.RooExtensions.*



class FormFieldsItdBuilder extends BeanPropertiesAwareItdBuilder<FormComponentMetadata>{
	
	public static String CREATE_AS_FORMCOMPONENT_METHOD = "createAsFormComponent"
	
	override FormFieldsMetadata getMetadata(){super.metadata as FormFieldsMetadata} 
		
	override String baseClassStereotype(){
		Stereotypes::FORM_FIELDS	
	}
	
	override getMethods()
	{
			var methods = constructors
			methods += getCreateComponentMethods(propertiesForScaffolding) 
			methods += getCreateFieldsMethod
			methods += getObjectClassMethod
			methods
	}
	
	def getConstructors(){
		newArrayList(
			constructorWithId,
			constructorWithModel,
			constructorWithIdAndModel
		)
	}
	
	def getCreateFieldsMethod(){
		val returnType = "java.util.List".javaType("org.apache.wicket.Component")
		method(
			signature(
				Modifier::PUBLIC, returnType, "createFields"
			),
			[|'''
			«returnType.resolve» fields = new «"java.util.ArrayList".javaType("org.apache.wicket.Component").resolve»();
			«FOR p : propertiesForScaffolding»
				fields.add(«p.getCreateComponentMethodName»());
			«ENDFOR»
			return fields;
			''']
			
		)
	}	
	

	
	override getCreateComponentMethodName(BeanPropertyMetadata p){
		"create"+p.getPropertyName.symbolNameCapitalisedFirstLetter+"Field"
	}
	
	override ClassOrInterfaceTypeDetails getDecoratorClass(){
		Stereotypes::COMPLEX_FORMFIELD.stereotypeDetails
	}
	
	override MethodMetadata getDecoratorMethodToOverride(){
		decoratorClass.findRequiredMethodWithStereotype(Stereotypes::CREATE_COMPONENT_METHOD)
	}
	
	override ClassOrInterfaceTypeDetails getListComponentClass(BeanPropertyMetadataWithDetails p){
		if(p.componentMetadata == null){
			Stereotypes::SIMPLE_LIST_EDITOR_FIELD.stereotypeDetails		
		} else {
			Stereotypes::COMPLEX_LIST_EDITOR_FIELD.stereotypeDetails	
		}
	}
	
	override MethodMetadata getListComponentMethodToOverride(ClassOrInterfaceTypeDetails listComponentClass){
		listComponentClass.getMethod("createItemComponent".symbol) //TODO: Stereotype Annotation on the method? 
	}
	
	
}